package com.pushwish.server;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

import com.pushwish.client.GreetingService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {
	private static final Logger log = Logger.getLogger(GreetingServiceImpl.class.getName());

	public String greetServer(String input) throws IllegalArgumentException {
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		
		// Escape data from the client to avoid cross-site script vulnerabilities.
		userAgent = escapeHtml(userAgent);
		ServerConfig.shutout = !ServerConfig.shutout;
		String message = "Server is " + (ServerConfig.shutout ? "quiet":"shouting") + "!<br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent + " coming from " + getThreadLocalRequest().getRemoteAddr()
				+ " at " + new SimpleDateFormat("yyyy/MM/dd hh:mm").format(new Date());
		
		// Push message to GTalk
		try {
			new PushwishToGTalk("guyuchun1969@gmail.com").push(message);
		} catch (IOException e) {
			log.severe(e.getMessage());
		}
		
		// Push message to GMail
		try {
			new PushwishToGMail().push(message);
		} catch (IOException e) {
			log.severe(e.getMessage());
		}
		return message;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
